<?php

namespace app\admin\controller;

use app\common\controller\Backend;
use think\Db;
use fast\Random;
use think\exception\PDOException;
use think\exception\ValidateException;
/**
 *
 *
 * @icon fa fa-circle-o
 */
class Dispatch extends Backend
{

    /**
     * Dispatch
     * @var \app\admin\model\Dispatch
     */
    protected $noNeedLogin = ['test'];
    protected $model = null;
    protected $fiveindustryArr = [];
    protected $streetArr = [];
    protected $industryCategoryArr = [];
    protected $tablename = 'dispatch';
    protected $year;
    protected $chargedep_data = null;
    protected $pre = '';
    protected $project_socialized = [];
    public function _initialize()
    {
        parent::_initialize();

        // $this -> year = $this -> request -> get('year',date('Y'));
        $this->model = new \app\admin\model\Dispatch;
        // $this -> model -> table = 'nsig_project_2020';
        $this->chargedep_model = new \app\admin\model\Chargedep;

        $this -> year = $this -> request -> get('year',date('Y'));
        // $this->projectmodel = new \app\admin\model\Project([],$this -> year);
        $this->projectmodel = new \app\admin\model\Project();
        // project_2021
        $this->newmodel = new \app\admin\model\Project_2021();


        $groupIds = $this->auth->getGroupIds();
        $this->assignconfig('isSuperAdmin',$this->auth->isSuperAdmin());
        $this->assign('isSuperAdmin',$this->auth->isSuperAdmin());
        $this->assignconfig('uid',$this->auth->id);
        // $this -> assign('year',$this -> year);
        $this->chargedep_data = $this->auth->getChargedep();

        if($this->chargedep_data)
        {
            $chargedep_id = $this->chargedep_data->chargedep_id;
            $this->assignconfig('isbinddep',1);
        }
        else
        {
            $chargedep_id = 0;
            $this->assignconfig('isbinddep',0);
        }

        $this->assignconfig('chargedep_id',$chargedep_id);
        if($this->auth->isSuperAdmin())
            $this->pre = '';
        else
            $this->pre = 'tmp_';
        $this->assign('pre',$this->pre);
        $this->assignconfig('pre',$this->pre);
    }

    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */

    public function index() {
        //设置过滤方法
        $this->request->filter(['strip_tags']);

        $groupIds = $this->auth->getGroupIds();

        if(!$this->auth->isSuperAdmin())
        {
            $chargedep_data = $this->auth->getChargedep();
            if(in_array(GROUP_DISTRICTUNIT,$groupIds) ||  in_array(GROUP_SOE,$groupIds)){
                if(isset($chargedep_data->chargedep_id)){
                    $chargedep_id = $chargedep_data->chargedep_id;
                    $this->whereExtend[] = ['exp',Db::raw("FIND_IN_SET($chargedep_id,chargedep_ids)")];
                    $this->assignconfig('chargedep_id',$chargedep_id);
                }
                $this->whereExtend['status'] = 0;
            }
            if(in_array(GROUP_STREET,$groupIds))
            {
                $chargedep_id = $chargedep_data->chargedep_id;
                $this->whereExtend[] = ['exp',Db::raw("FIND_IN_SET($chargedep_id,chargedep_ids)")];
                $this->assignconfig('chargedep_id',$chargedep_id);
            }
            //各个端口都只能看审核完的
        }
        // 管理员可以看全部
        // $this->whereExtend['library_id'] = DISPATCH;
        $this->whereExtend['is_delete'] = 0;

        // pr($this->model);
        // exit();
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            $exp = new \think\db\Expression('field(status,1,0,-1)');
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $total = $this->model
                // ->with($this->relationtTable)
                ->where($where)
                ->where($this->whereExtend)
                ->count();

            if($total != 0){
                $exp = new \think\db\Expression('field(status,1,0,-1)');
            }else{
                $exp = '';
            }

            $list = $this->model
                // ->with($this->relationtTable)
                ->where($where)
                ->where($this->whereExtend)
                ->order($this->sortExtend)
                ->order($exp )
                ->limit($offset, $limit)
                ->select();
            // echo $this->model->getLastSql();

            $list = collection($list)->toArray();
            $result = array("total" => $total, "rows" => $list);

            return json($result);
        }
        return $this->view->fetch();

    }
    public function add(){
        $field_arr = ['name','investment_total','framework_agreement_time','invesment_agreement_time','project_source_ids'];
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                $params = $this->preExcludeFields($params);

                if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
                    $params[$this->dataLimitField] = $this->auth->id;
                }
                foreach ($field_arr as $key => $value) {
                    if(isset($params[$value]) && $params[$value]) {
                        $insert_data['tmp_'.$value] = $params[$value];
                        $insert_data['tmp_'.$value.'_status'] = STATUS_SUBMIT;
                        if($value=='project_source_ids')
                        {
                            $activity = (new \app\admin\model\Activity)->where(['id'=>$params[$value]])->find();
                            $insert_data['tmp_project_source_names'] = $activity['name'];
                            if($activity['name']=='区领导见签'||$activity['name']=='市领导见签')
                                $insert_data['is_important'] = 1;
                            else
                                $insert_data['is_important'] = $activity['is_important'];
                        }

                    }
                }
                $insert_data['name'] = $params['name'];
                $insert_data['tmp_name'] = null;
                $insert_data['tmp_name_status'] =200;
                if(!$this -> auth -> isSuperAdmin()){
                    $insert_data['chargedep_ids'] = $this->chargedep_data->chargedep_id;
                    $insert_data['chargedep_names'] = $this->chargedep_data->nickname;
                    $insert_data['settle_street_ids'] = $this->chargedep_data->chargedep_id;
                    $insert_data['settle_street_names'] = $this->chargedep_data->nickname;
                    // $insertData['status'] = 1;
                }else{
                    if (isset($params['settle_street_ids'])) {
                        $row_info = $this->chargedep_model->get($params['settle_street_ids']);
                        $accompany_name = $row_info->name?$row_info->name:"";
                        $insert_data['settle_street_ids'] = $params['settle_street_ids'];
                        $insert_data['settle_street_names'] = $accompany_name;
                        $insert_data['chargedep_ids'] = $params['settle_street_ids'];
                        $insert_data['chargedep_names'] = $accompany_name;
                    }

                }
                $insert_data['library_id'] = DISPATCH;
                $insert_data['library_name'] = '旬调度签约项目';
                $insert_data['is_add'] = 1;
                $insert_data['add_memo'] = '新增';
                $insert_data['is_visible'] = 0;
                $insert_data['status'] = 1;
                $insert_data['pno'] = Random::uuid();
                $project_row = $this->projectmodel->where(['name'=>$params['name']])->find();
                if($project_row)
                    $insert_data['project_pno'] = $project_row['pno'];
                // pr($insert_data);exit();

                $result = false;
                Db::startTrans();
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : $name) : $this->modelValidate;
                        $this->model->validateFailException(true)->validate($validate);
                    }
                    $result = $this->model->allowField(true)->save($insert_data);
                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were inserted'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $chargedep_list = $this->chargedep_model::where([])->select();
        $this->assign('chargedep_list',$chargedep_list);

        $activity_list = (new \app\admin\model\Activity)->where(['year'=>['in',[0,date('Year')]]])->select();
        $this->assign('activity_list',$activity_list);

        return $this->view->fetch();

    }
    public function edit($ids = NULL) {
        $row = $this->model->get($ids);
        if (!$row) {
            exit($ids);
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            if (!in_array($row[$this->dataLimitField], $adminIds)) {
                $this->error(__('You have no permission'));
            }
        }
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            $re_params = $this->request->post("relation/a");
            if ($params) {
                $params = $this->preExcludeFields($params);
                $project_params = [];
                // $field = $this->request->post("item_id");
                $status = 0;
                $updateData = [];
                               foreach ($params as $key => $value) {
                    // pr($value);
                    if(!$value){
                        if(isset($re_params[$key]) && $re_params[$key]==1){
                            $updateData['tmp_'.$key] = null;
                            $updateData['tmp_'.$key.'_status'] = 100;
                            $status = 1;
                        }
                        continue;
                    }

                    if(isset($row -> $key) &&  $params[$key] != $row[$key]){
                        if(is_int($row -> $key) && (substr($key,-5) == '_time') && date("Y-m-d",$row -> $key) == $params[$key]) continue;
                        $status = 1;
                        $updateData['tmp_'.$key] = $params[$key];
                        $updateData['tmp_'.$key.'_status'] = 100;

                        if($key=='project_source_ids')
                        {
                            $activity = (new \app\admin\model\Activity)->where(['id'=>$value])->find();
                            $updateData['tmp_project_source_names'] = $activity['name'];
                            $updateData['is_important'] = $activity['is_important'];
                        }
                    }
                }
                $updateData['status'] = $status;

                // 管理员不用审核
                if($this -> auth -> isSuperAdmin()){
                    if(isset($updateData['tmp_settle_street_ids']))
                    {
                        $row_info = $this->chargedep_model->get($updateData['tmp_settle_street_ids']);
                        $accompany_name = $row_info->name?$row_info->name:"";
                        $updateData['chargedep_ids'] = $updateData['tmp_settle_street_ids'];
                        $updateData['chargedep_names'] = $accompany_name;
                        $updateData['settle_street_ids'] = $updateData['tmp_settle_street_ids'];
                        $updateData['settle_street_names'] = $accompany_name;
                    }
                }
                $result = false;
                Db::startTrans();
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                        $row->validateFailException(true)->validate($validate);
                    }
                    // pr($updateData);
                    $result = $row->allowField(true)->save($updateData);
                    // pr($project_params);
                    $wherevalue = $row['project_pno']??$row['name'];
                    $dispatchLogic = \app\admin\logic\Dispatch::instance();
                    $dispatchLogic->updatePorject(2020, $params, $wherevalue);
                    $dispatchLogic->updatePorject(2021, $params, $wherevalue);

                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were updated'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $this->assignconfig('ids',$ids);
        $this->view->assign("row", $row);

        $chargedep_list = $this->chargedep_model::where([])->select();
        $this->assign('chargedep_list',$chargedep_list);

        $year = $row['year']?$row['year']:date('Year');

        $activity_list = (new \app\admin\model\Activity)->where(['year'=>['in',[0,$year]]])->select();

        $this->assign('activity_list',$activity_list);

        return $this->view->fetch();
    }

    public function initedit($ids) {

        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            if (!in_array($row[$this->dataLimitField], $adminIds)) {
                $this->error(__('You have no permission'));
            }
        }
        if ($this->request->isPost()) {
            $data = $this->request->post("row/a");
            if ($data) {
                $data = $this->preExcludeFields($data);

                $updateData = [];

                foreach ($data as $k => $v) {

                    if(isset($row -> $k) && $row -> $k != (is_array($data[$k]) ? implode(',',$data[$k]) : $data[$k])){
                        if(is_int($row -> $k) && (substr($k,-5) == '_time') && date("Y-m-d",$row -> $k) == $data[$k]) continue;
                        $key = $this -> auth -> isSuperAdmin() ? $k : 'tmp_'.$k;
                        $updateData[$key] = $data[$k];
                        $updateData[$key.'_status'] = STATUS_SUBMIT;
                        if(isset($data[$k.'_submit_desc']))
                            $updateData[$key.'_submit_desc'] = $data[$k.'_submit_desc'];
                        // $logData[] = [
                        //     'approach_id' => $row -> id,
                        //     'admin_id'  => $this -> auth -> id,
                        //     'admin_nickname' => $this->auth->nickname,
                        //     'field' => $k,
                        //     'field_name' => $this -> tmpFieldNames[$k] ?? ($this -> fieldNames[$k] ?? ''),
                        //     'ori_value' => $row -> $k,
                        //     'new_value' => is_array($data[$k]) ? implode(',',$data[$k]) : $data[$k],
                        //     'status' =>  100,
                        //     'info'  => $this -> auth -> isSuperAdmin() ? '管理员修改' : '申请提交',
                        //     'desc' => isset($data[$k.'_submit_desc'])?$data[$k.'_submit_desc']:'',
                        //     'create_time' => time(),
                        //     'update_time'   => time()
                        // ];
                    }
                }
                if($updateData)
                    $updateData['status'] = $this -> auth -> isSuperAdmin() ? 0 : 1;
                // pr($logData);
                // pr($updateData);
                // if($logData){
                //     Db::name('approachlog') -> insertAll($logData);
                // }
                // if($updateData){
                //     // if(!$this -> auth -> isSuperAdmin()){
                //     //     $updateData['status'] = 100;
                //     // }

                //     $ret = $row -> save($updateData);
                // }

                // var_dump($updateData);exit();
                // $result = false;
                Db::startTrans();
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                        $row->validateFailException(true)->validate($validate);
                    }
                    $result = $row->allowField(true)->save($updateData);

                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    // if($logData){
                    //     Db::name('approachlog') -> insertAll($logData);
                    // }
                    $this->success();
                } else {
                    $this->error(__('No rows were updated'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $this->view->assign("row", $row);
        return $this->view->fetch();
    }

    public function checkedit($ids = null){
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $field = ['name','investment_total','framework_agreement_time','invesment_agreement_time','project_source_ids'];
        if ($this->request->isPost()) {
            $data = [];
            // $params = $this->request->post("row/a");
            foreach ($field as  $value) {
                if(isset($row['tmp_'.$value.'_status']) && $row['tmp_'.$value.'_status'] == 100)
                {
                    $data['tmp_'.$value.'_status'] = null;
                    $data[$value] = $row['tmp_'.$value];
                    $data['tmp_'.$value] = null;

                    if($value=='project_source_ids'){
                        $data['project_source_names'] = $row['tmp_project_source_names'];
                        $data['tmp_project_source_names'] = null;
                    }

                }
            }
            $data['status'] = 0;
            $data['is_visible'] = 1;
            // $data['is_add'] = 0;//各个端口审核完的项目都不标红，
            // pr($data);
            $project_pno = Random::uuid();

            // pr($data);
            // exit;
            // 判断是否存在
            $result = false;
            $wherevalue = $row['project_pno']??$row['name'];
            if(!$row->project_pno)
                $data['project_pno'] = $project_pno;
            $result = $row->allowField(true)->save($data);

            $dispatchLogic = \app\admin\logic\Dispatch::instance();
            $dispatchLogic->addProject($wherevalue,$row);

            if ($result !== false) {
                $this->success();
            } else {
                $this->error(__('No rows were updated'));
            }

        }
        $this->assignconfig('ids',$ids);
        $this->view->assign("row", $row);
        return $this->view->fetch();
    }

    public function detail($ids = null){
        if(!$ids){
            $this -> error('请刷新重试');
        }

        $row = $this -> model -> find($ids);

        $this -> assign('row',$row);
        return $this -> fetch();
    }

    public function del($ids = null ){
        $ids = $ids ? $ids : $this->request->param("ids");
        $row = $this -> model -> find($ids);
        if(!$row)
            $this->error('记录不存在');
        $row->is_delete = 1;
        $row->save();
        $this->success();
        // $this -> assign('row',$row);
        // return $this -> fetch();
    }
    //
    public function export(){
        ini_set('memory_limit', '999M');

        $xlsName = '旬调度数据导出';
        $groupIds = $this->auth->getGroupIds();

        if(/*in_array(GROUP_DISTRICTUNIT,$groupIds) || */in_array(GROUP_STREET,$groupIds) || in_array(GROUP_SOE,$groupIds))
        {
            $chargedep_data = $this->auth->getChargedep();
            if($chargedep_data){
                $chargedep_id = $chargedep_data->chargedep_id;
                $this->whereExtend[] = ['exp',Db::raw("FIND_IN_SET($chargedep_id,chargedep_ids)")];
                $this->assignconfig('chargedep_id',$chargedep_id);
            }
            $showAna = false;
        }
        if(in_array(GROUP_DISTRICTUNIT,$groupIds) || in_array(GROUP_DISTRICTUNIT,$groupIds))
        {
            // $this->whereExtend['is_add'] = 1;
            // $this->whereExtend['is_visible'] = 1;
        }
        list($where, $sort, $order, $offset, $limit) = $this->buildparams();
        $list = $this->model->with($this->relationtTable)
            ->where($where)
            ->where($this->whereExtend)
            ->where(['library_id' => DISPATCH , 'is_visible' => 1,'is_delete'=>0])
            ->select();
        $total = $this->model->with($this->relationtTable)
            ->where($where)
            ->where($this->whereExtend)
            ->where(['library_id' => DISPATCH , 'is_visible' => 1,'is_delete'=>0])
            ->count();
        if($total == 0)
            $this->error('暂无数据导出');
        $xlsDataReal = [];
        $xlsCell = array('序号','项目名称','总投资(亿元)','落户街道','签订框架协议时间','签订正式投资协议时间');
        foreach ($list as $key => $value) {
            $xlsDataReal[] = [
                ++$key,
                $value['name'],
                $value['investment_total'],
                $value['settle_street_names'],
                $value['framework_agreement_time_text'],
                $value['invesment_agreement_time_text']
            ];

        }
        // pr($xlsDataReal);
        exportExcel($xlsName,'Excel2007', $xlsDataReal, $xlsCell);
    }


}
